/** 
 * @Project ZmkmUserSdk
 * @Filename ZMKMUSER_CommonUtils.java 
 * @Package com.wifiunion.zmkm.utils 
 * @Description TODO 
 * @Author wifiunion
 * @Creation 2016年1月25日 下午2:32:36 
 * @Modification 2016年1月25日 下午2:32:36    
 * @Copyright Copyright © 2012 - 2016 wifiunion.All Rights Reserved.
 **/
package com.wifiunion.zmkm.utils;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Random;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.wifiunion.zmkm.entity.User;
import com.wifiunion.zmkm.entity.UserAddressEntity;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.util.Log;

/**
 * @ClassName ZMKMUSER_BitmapUtils
 * @Description TODO
 * @Version 1.0
 * @Author wifiunion
 * @Creation 2016年1月25日 下午2:32:36
 * @Modification 2016年1月25日 下午2:32:36
 **/
public class ZMKMUSER_BitmapUtils {

	/**
	 * 获取二维码
	 * 
	 * @Name getQrCodeBitmap
	 * @Description TODO
	 * @param context
	 * @param fmUuid
	 * @return
	 * @return Bitmap
	 * @Author wifiunion
	 * @Date 2016年1月29日 下午1:51:02
	 * 
	 */
	public static Bitmap getQrCodeBitmap(Context context, final String fmUuid) {

		UserAddressEntity addressInfo = getUserAddressInfo(context, fmUuid);
		Bitmap qrcodeBitmap = null;
		if (addressInfo == null) {
			return null;
		} else {
			qrcodeBitmap = getBitmap(context, addressInfo);
		}
		return qrcodeBitmap;
	}

	/**
	 * 
	 * @Name getQrCodeBitmap
	 * @Description TODO
	 * @param context
	 * @param fmUuid
	 * @param qrcodeSize
	 *            指定qrcode的大小
	 * @return
	 * @return Bitmap
	 * @Author wifiunion
	 * @Date 2016年1月29日 下午1:52:16
	 *
	 */
	public static Bitmap getQrCodeBitmap(Context context, String fmUuid, int qrcodeSize, Handler handler) {
		
		
		UserAddressEntity addressInfo = getUserAddressInfo(context, fmUuid);
		Bitmap qrcodeBitmap = null;
		if (addressInfo == null) {
			return null;
		} else {
			qrcodeBitmap = getBitmap(context, addressInfo, qrcodeSize);
		}
		return qrcodeBitmap;
	}

	private static UserAddressEntity getUserAddressInfo(Context context, String fmUuid) {

		LinkedList<UserAddressEntity> userAddressList = new LinkedList<UserAddressEntity>();

		User user = (User) ZMKMUSER_CommonUtils.readObject(context, ZMKMUSER_Constant.CONFIG_USER);
		if (user != null) {
			userAddressList = user.getAddresses();
			if (userAddressList != null) {
				if (userAddressList.size() > 0) {
					for (UserAddressEntity address : userAddressList) {
						if (fmUuid.equals(address.getFmUuid())) {
							return address;
						}
					}
				}
			}
		}
		return null;
	}

	/**
	 * 
	 * @param user
	 * @param ctx
	 * @return
	 */
	private static String getQRCodeString(UserAddressEntity addressInfo, Context ctx) {
		byte[] qrcode = getQRByte(addressInfo, ctx);
		try {
			return new String(qrcode, "ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 创建二维码图片
	 * 
	 * @param [codeStr]
	 *            [二维码字符串]
	 * @param [widthOR]
	 *            [大小]
	 * @return [二维码图片]
	 */
	private static Bitmap createQRCode(String codeStr, int widthOR) throws WriterException {
		Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
		hints.put(EncodeHintType.CHARACTER_SET, "ISO-8859-1");
		BitMatrix matrix = new MultiFormatWriter().encode(codeStr, BarcodeFormat.QR_CODE, widthOR, widthOR, hints);

		int width = matrix.getWidth();
		int height = matrix.getHeight();
		int[] pixels = new int[width * height];

		boolean isFirstBlackPoint = false;
		int startX = 0;
		int startY = 0;

		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				if (matrix.get(x, y)) {
					if (isFirstBlackPoint == false) {
						isFirstBlackPoint = true;
						startX = x;
						startY = y;
					}
					pixels[y * width + x] = 0xff000000;
				} else {
					pixels[y * width + x] = 0xffffffff;
				}
			}
		}

		Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

		if (startX <= 0)
			return bitmap;

		int x1 = startX - 0;
		int y1 = startY - 0;

		if (x1 < 0 || y1 < 0)
			return bitmap;

		int w1 = width - x1 * 2;
		int h1 = height - y1 * 2;

		Bitmap bitmapOne = Bitmap.createBitmap(bitmap, x1, y1, w1, h1);

		bitmapOne = Bitmap.createScaledBitmap(bitmapOne, widthOR, widthOR, true);

		return bitmapOne;
	}

	/**
	 * 
	 * @Name getBitmap
	 * @Description TODO
	 * @param context
	 * @param addressInfo
	 * @return 默认大小的二维码 250
	 * @return Bitmap
	 * @Author wifiunion
	 * @Date 2016年1月29日 下午1:48:35
	 * 
	 */
	public static Bitmap getBitmap(Context context, UserAddressEntity addressInfo) {
		String bit = getQRCodeString(addressInfo, context);
		Bitmap bmp = null;
		try {
			bmp = createQRCode(bit, 400);
		} catch (WriterException e) {
			e.printStackTrace();
		}
		return bmp;
	}

	/**
	 * 
	 * @Name getBitmap
	 * @Description TODO
	 * @param context
	 * @param addressInfo
	 * @param size
	 *            二维码大小
	 * @return
	 * @return Bitmap
	 * @Author wifiunion
	 * @Date 2016年1月29日 下午1:48:16
	 * 
	 */
	public static Bitmap getBitmap(Context context, UserAddressEntity addressInfo, int size) {
		String bit = getQRCodeString(addressInfo, context);
		Bitmap bmp = null;
		try {
			if (size <= 500) {
				bmp = createQRCode(bit, size);
			} else {
				bmp = createQRCode(bit, 500);
			}
		} catch (WriterException e) {
			e.printStackTrace();
		}
		return bmp;
	}

	/**
	 * 
	 * @param user
	 * @param ctx
	 * @return
	 */
	public static byte[] getQRByte(UserAddressEntity addressInfo, Context ctx) {
		// 二维码串
		MakeCode makeCode = new MakeCode();
		String qr = makeCode.makecard(0, getCodeDate(addressInfo, ctx));
		// 前缀
		// String strHex = "02A879C30B";
//		byte[] qrData = SimpleCrypto.getBytes(qr.toCharArray());
//		String qrHex = SimpleCrypto.toHex(qrData);
//		qrHex = qrHex + hexRandom() + "2EF0";// 2DF0
//		// 开始手机号码
//		qrHex = qrHex + "50";
//		String phoneNumber = ZMKMUSER_SharePUtils.getSharedPreferences(ZMKMUSER_Constant.CONFIG_PHONE, ctx);
//
//		String phone = String.format("%012d", Long.parseLong(phoneNumber));
//		String newPhone = "";
//		for (int i = 0; i < phone.length(); i += 2) {
//			String temp = phone.substring(i, i + 2);
//			String newTemp = Integer.toHexString(Integer.valueOf(temp));
//			if (newTemp.length() == 1) {
//				newTemp = "0" + newTemp;
//			}
//			newPhone += newTemp;
//		}
//		qrHex = qrHex + newPhone+ "1D";
//		// 开始异或运算
//		int CRC = yihuo(SimpleCrypto.toByte(qrHex));
//		String hexCrc = Integer.toHexString(CRC);
//		if (hexCrc.length() == 1) {
//			hexCrc = "0" + hexCrc;
//		}
//		qrHex = qrHex + hexCrc;
//		
//		byte[] data = SimpleCrypto.toByte(qrHex);
		
		byte[] qrData = SimpleCrypto.getBytes(qr.toCharArray());
        String qrHex = SimpleCrypto.toHex(qrData);
        qrHex = qrHex + hexRandom() + "2EF0";// 2DF0
        // 开始手机号码
        qrHex = qrHex + "50";
        String phoneNumber = ZMKMUSER_SharePUtils.getSharedPreferences(ZMKMUSER_Constant.CONFIG_PHONE, ctx);
        String phone = String.format("%012d", Long.parseLong(phoneNumber));
        String newPhone = "";
        for (int i = 0; i < phone.length(); i += 2) {
            String temp = phone.substring(i, i + 2);
            String newTemp = Integer.toHexString(Integer.valueOf(temp));
            if (newTemp.length() == 1) {
                newTemp = "0" + newTemp;
            }
            newPhone += newTemp;
        }
        qrHex = qrHex + newPhone + "1D";
        // 开始异或运算
        int CRC = yihuo(SimpleCrypto.toByte(qrHex));
        String hexCrc = Integer.toHexString(CRC);
        if (hexCrc.length() == 1) {
            hexCrc = "0" + hexCrc;
        }
        qrHex = qrHex + hexCrc;
        byte[] data = SimpleCrypto.toByte(qrHex);

		return data;
	}

	// 开始异或运算
	private static int yihuo(byte[] data) {
		int CRC = 0;
		char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		for (byte b : data) {
			StringBuilder buf = new StringBuilder();
			buf.append(HEX_DIGITS[(b >> 4) & 0x0f]);
			buf.append(HEX_DIGITS[b & 0x0f]);
			// System.out.println("buf=="+buf);
			CRC ^= Integer.parseInt(buf.toString(), 16);
		}
		return CRC;
	}

	public static String getCodeDate(UserAddressEntity addressInfo, Context ctx) {
		int time = addressInfo.getTime();
		time = time == 0 ? 30 : time;
		Date now = new Date();
		Date now_0 = new Date(now.getTime()); //
		Date now_10 = new Date(now.getTime() + (60000 * time)); //
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmss");// 可以方便地修改日期格式
		String nowTime_0 = dateFormat.format(now_0);
		String nowTime_10 = dateFormat.format(now_10);
		/******************************************************/
		Date now_1 = new Date(now.getTime() - (60000 * time));
		String nowTime_1 = dateFormat.format(now_1);

		String codeDate = "C1,M" + addressInfo.getM() + ",S" + nowTime_1 + ",I" + nowTime_1 + ",O" + nowTime_10
				+ ",X0,B" + addressInfo.getB() + ",F" + addressInfo.getF() + ",R" + addressInfo.getR() + ",D"
				+ addressInfo.getD() + ",N" + addressInfo.getN();
		
		return codeDate;
	}

	// 返回0到256的随机流水号，十六机制
	private static String hexRandom() {
		Random r = new Random();
		int i = r.nextInt(256);
		String hexRandom = Integer.toHexString(i);
		if (hexRandom.length() == 1) {
			hexRandom = "0" + hexRandom;
		}
		return hexRandom;
	}

}
